/*
str_contentDivId: 生成plugin 的div id
str_idPrefix: id 前缀;
obj_dataGridParameter: 产生dataGrid的参数
					其中左侧datagrid使用的属性如下：
					url : obj_dataGridParameter.url,
					sortName : obj_dataGridParameter.sortName,
					sortOrder : obj_dataGridParameter.sortOrder, 
					columns:obj_dataGridParameter.columns,

					其中右侧使用的属性如下：
					obj_dataGridParameter.columns


obj_filterClass: 格式如：{'className':'project','fieldNames':['name','sn']}
				该参数用于生成筛选条件,如 project.name   project.sn
				其中 className, 在生成查询条件是上例中的project
					fieldNams,在生成查询条件是上例中的project的属性名组成的数组

array_initRightDatagridRow, 初始化时，rightDatagrid已经有的row like [{"productid":"AV-CB-01","productname":"Amazon Parrot"}]
fun_okCall: 回调函数如下:
			funcName(array_rows)，其中 array_rows 为右侧datagrid 的调用getData 返回的rows.


array_customFun:array_customFun:自定义参数:格式为[{label:"新增",function:funA}]
*/

function ldrdSelect(
	str_contentDivId,
	str_idPrefix,
	str_dlgTitle,
	obj_dataGridParameter,
	obj_filterClass,
	array_initRightDatagridRow,
	fun_okCall,array_customFun){

	console.log(array_initRightDatagridRow);
	ldrdSelect_createPanelAndLayout(str_idPrefix,str_contentDivId);
	ldrdSelect_createEzDatagrid(str_idPrefix,obj_dataGridParameter,array_initRightDatagridRow);
	ldrdSelect_registerInnerFunctionButtons(str_idPrefix,obj_filterClass,fun_okCall);
	ldrdSelect_registerCustomFunction(str_idPrefix,array_customFun);

}


function ldrdSelect_createPanelAndLayout(str_idPrefix,
			str_contentDivId,str_dlgTitle){
			var str_panel=["<div  class=\"easyui-panel\" data-options=\"noheader:true\" style=\"width:950px;height:500px;\" ></div>"].join("");
			var div_panel=$(str_panel).attr("id",str_idPrefix+"-ldrdSelect-panel");

			var str_layout=["<div  class=\"easyui-layout\" data-options=\"fit:true\" ></div>"].join("");
			var div_layout=$(str_layout).attr("id",str_idPrefix+"-ldrdSelect-layout");

			var str_westRegion=["<div data-options=\"region:\'west\',iconCls:\'icon-reload\',title:\'查询选择\' , collapsible:false ,border:false\" style=\"width:400px;\">",
						"<div  style=\"vertical-align: middle;border-bottom: 1px solid #E3E3E3;\">",
						"<label for=\"exampleInputName2\" style=\"margin-left: 10px;\">关键词</label>",
						"<input id=\""+str_idPrefix+"-ldrdSelect-keyword\" type=\"text\" style=\"width: 70px;margin: 0 5px 0 5px;\" placeholder=\"\" >",
						"<button type=\"button\" class=\"\" id=\""+str_idPrefix+"-ldrdSelect-filter\">筛选</button>",
						"<button type=\"button\" class=\"\" id=\""+str_idPrefix+"-ldrdSelect-reset\">清除</button>",
						"</div>",
						/*"<div  class=\"easyui-panel\" data-options=\"border:false,noheader:true,fit:false\">",*/
						"<table id=\""+str_idPrefix+"-ldrdSelect-lDatagrid\" ></table>",
						/*"</div>",*/
						"</div>   "].join("");					
			var div_westRegion=$(str_westRegion);

			var str_centerRegion=["<div data-options=\"region:\'center\'\" style=\"background:#eee;width:70px ;\">",
						"  <div class=\"operators\" style=\'text-align: center;\'>",
						"    <ul id=\""+str_idPrefix+"-ldrdSelect-ul\" style=\"list-style: none;padding-left: 0px;padding-top: 70px;text-align: center;line-height:40px;\">",
						"   <li>",
						"        <input type=\"button\" id=\""+str_idPrefix+"-ldrdSelect-right_all\" value=\" >> \" style=\"width: 55px;height: 25px;\" //></li>",
						"   <li>",
						"        <input type=\"button\" id=\""+str_idPrefix+"-ldrdSelect-left_all\" value=\" << \" style=\"width: 55px;height: 25px;\" //></li>",
						"    </ul>",
						"  </div>",
						"</div>"].join("");
			var div_centerRegion=$(str_centerRegion);

			var str_eastRegion=["<div data-options=\"region:\'east\',iconCls:\'icon-reload\',title:\'已选择\' , collapsible:false ,border:false\" style=\"width:400px;\">",
								"<table id=\""+str_idPrefix+"-ldrdSelect-rDatagrid\"></table>",
								"</div>"].join("");				
			var div_eastRegion=$(str_eastRegion);

			var str_southRegion=["<div data-options=\"region:\'south\',iconCls:\'icon-reload\' , collapsible:false,doSize:true\" style=\"height:40px;\">",
						"  <div style=\"text-align: center;margin-top: 5px;\">",
						"    <button id=\""+str_idPrefix+"-ldrdSelect-cancle\">取消</button>",
						"    <button id=\""+str_idPrefix+"-ldrdSelect-ok\" style=\"margin-left: 20px;\">确认</button></div>",
						"	<div id=\""+str_idPrefix+"-ldrdSelect-data\" data-ltrdData=\"[]\">",
						"</div>"].join("");
			var div_southRegion=$(str_southRegion);
	
			//div 合并
			$("#"+str_contentDivId).append(div_panel);
			div_panel.append(div_layout);
			div_layout.append(div_westRegion,div_centerRegion,div_eastRegion,div_southRegion);
			
			//生成 pannel、layout 对象
			var ez_panel=div_panel.dialog({    
			    width:970,    
			    height: 650,
			    title: str_dlgTitle,
			    closed: false,    
			    cache: false,    
			    modal: true,
			    noheader:false,
			    closable:false
			    
			   	//queryParams:lrDlgQueryParams,
			   	//method:'post'
			}); 
			div_layout.layout();


		}

		//构建dataGridEz对象
		//str_idPrefix：id 前缀,obj_dataGridParameter: 构建datagrid 的参数
		//目前属性 obj_treeParameter：url;queryParams
		function ldrdSelect_createEzDatagrid(str_idPrefix,obj_dataGridParameter,array_initRightDatagridRow){
			var str_lDatagridId=str_idPrefix+"-ldrdSelect-lDatagrid";
			var str_rDatagridId=str_idPrefix+"-ldrdSelect-rDatagrid";

			console.log(obj_dataGridParameter);
			var ez_lDatagrid=$("#"+str_lDatagridId).datagrid({
					url : obj_dataGridParameter.url,
					method:"get",
					fit : true,
					fitColumns : true,
					singleSelect:true,
					border : true,
					pagination : true,
					rownumbers:true,
					idField : 'productid',
					pageSize : 10,
					pageList : [ 10, 20, 30, 40, 50 ],
					sortName : obj_dataGridParameter.sortName,
					sortOrder : obj_dataGridParameter.sortOrder, 
					//multiSort : true,
					striped: true,
					checkOnSelect : false,
					selectOnCheck : false,
					nowrap : false,
					columns:obj_dataGridParameter.columns,
					onSelect:function(index,row){
						console.log("ldatagrid Select");
						ldrdSelect_rightGridAddRow(row,$("#"+str_rDatagridId));
					}
					,
					/*onBeforeLoad : function(param){
						console.log(param);
						if(param.sort){
							param.webClass="contract";
							console.log(param);
						}
					}*/
			});

			var ez_rDatagrid=$('#'+str_rDatagridId).datagrid({    
				pagination:false,
				rownumbers:true,
				nowrap : false,
				fit:true,
				data:array_initRightDatagridRow,
			  /*	fitColumns:true,*/
			    columns:obj_dataGridParameter.columns,
			    onSelect:function(index,row){
						ez_rDatagrid.datagrid('deleteRow',index);
					}
			});
		}



		//obj_filterClass格式如：{'className':'project','fieldNames':['name','sn']}
		function ldrdSelect_registerInnerFunctionButtons(str_idPrefix,obj_filterClass,fun_okCall){
			//注册 文本框回车事件，回车直接筛选
			$('#'+str_idPrefix+'-ldrdsSelect-keyword').on('keydown',function(e){
				if(e.keyCode==13){
				  $("#"+str_idPrefix+"-ldrdSelect-filter").click();
				}
			});

			//注册筛选按钮事件
			$("#"+str_idPrefix+"-ldrdSelect-filter").on("click",function(){
				console.log("hit filter btn");
				console.log(obj_filterClass);
				var str_lDatagridId=str_idPrefix+"-ldrdSelect-lDatagrid";
				var jq_lDatagrid=$("#"+str_lDatagridId);
				var array_queryValue=new Array();
				var filter=new Object();//向后台传递参数，需转换成json.
				
				//obj_filterClass
				if(!obj_filterClass || !obj_filterClass.className || !obj_filterClass.fieldNames || obj_filterClass.fieldNames.length==0){
					console.log("keyword 信息错误");
					return;
				}

				//构造查询条件
				var value=$("#"+str_idPrefix+"-ldrdSelect-keyword").val();
				if(value.trim()==''){
					jq_lDatagrid.datagrid('load',{});
					return;
				}

				var values=value.split(' ');
				
				for (var i=0; i<values.length; i++){
					if(values[i].trim()!=''){
						array_queryValue.push("&"+values[i]);
					}
				}
				console.log(array_queryValue);

				

				var obj_queryFilterClass=new Object();
				obj_queryFilterClass.className=obj_filterClass.className;
				obj_queryFilterClass.fields=new Array();
				obj_queryFilterClass.fieldOperators=['or'];

				var array_classFieldNams=obj_filterClass.fieldNames;
				
				$.each(array_classFieldNams,function(){
					console.log(this);
					var obj_queryField={'fieldName':this,'values':array_queryValue};
					obj_queryField.valueOperators=['and'];
					obj_queryFilterClass.fields.push(obj_queryField);
				})
				
				var filterJson=JSON.stringify(obj_queryFilterClass);
				var testObj=new Object();
				testObj.name='abc';
				testObj.age='8';
				var testJson=JSON.stringify(testObj);
				console.log(filterJson);
				jq_lDatagrid.datagrid('reload',{
					'filterJson':filterJson,
					'testJson':testJson
				});
				
			});

			//清除筛选按钮事件
			$("#"+str_idPrefix+"-ldrdSelect-reset").on("click",function(){
				//console.log("clear");
				$("#"+str_idPrefix+"-ldrdSelect-keyword").val("");
				var str_lDatagridId=str_idPrefix+"-ldrdSelect-lDatagrid";
				var jq_lDatagrid=$("#"+str_lDatagridId);
				jq_lDatagrid.datagrid('load',{});
			});


			//注册 全右选事件
			$("#"+str_idPrefix+"-ldrdSelect-right_all").on("click",function(){
				var str_lDatagridId=str_idPrefix+"-ldrdSelect-lDatagrid";
				var jq_lDatagrid=$("#"+str_lDatagridId);
				var str_rDatagridId=str_idPrefix+"-ldrdSelect-rDatagrid";
				var jq_rDatagrid=$("#"+str_rDatagridId);
				


				var rows=jq_lDatagrid.datagrid('getRows');
				$.each(rows, function() {
					ldrdSelect_rightGridAddRow(this,jq_rDatagrid);
				});
			});
			
			
			//注册 全左选事件
			$("#"+str_idPrefix+"-ldrdSelect-left_all").on("click",function(){
				var str_rDatagridId=str_idPrefix+"-ldrdSelect-rDatagrid";
				var jq_rDatagrid=$("#"+str_rDatagridId);
				jq_rDatagrid.datagrid('loadData', { total: 0, rows: [] }); 
			});

			//注册取消事件
			$("#"+str_idPrefix+"-ldrdSelect-cancle").on("click",function(){
				var str_panelId=str_idPrefix+"-ldrdSelect-panel";
				var jq_panel=$("#"+str_panelId);
				jq_panel.panel("destroy");
				
			});
			
			//注册OK事件
			$("#"+str_idPrefix+"-ldrdSelect-ok").on("click",function(){
				var str_rDatagridId=str_idPrefix+"-ldrdSelect-rDatagrid";
				var jq_rDatagrid=$("#"+str_rDatagridId);
				var str_panelId=str_idPrefix+"-ldrdSelect-panel";
				var jq_panel=$("#"+str_panelId);	

				var rowArray=new Array();
				var obj_gridData=jq_rDatagrid.datagrid('getRows');
				fun_okCall(obj_gridData);

				jq_panel.panel("destroy");
			});
		}

		function ldrdSelect_rightGridAddRow(row,jq_dataGrid){
			/*
			var str_lDatagridId=str_idPrefix+"-ldrdSelect-lDatagrid";
			var jq_lDatagrid=$("#"+str_lDatagridId);
			var str_rDatagridId=str_idPrefix+"-ldrdSelect-rDatagrid";
			var jq_rDatagrid=$("#"+str_rDatagridId);*/
			//console.log();
			var canAdd=true;
			$.each(jq_dataGrid.datagrid('getRows'), function() {
				//console.log(this);
				if(this.id==row.id){
					canAdd=false;
				}
			});
			if(canAdd){
				jq_dataGrid.datagrid('appendRow',row);
			}
		}

		function ldrdSelect_registerCustomFunction(str_idPrefix,array_customFun){
			var str_ulId=str_idPrefix+"-ldrdSelect-ul";
			var jq_ul=$("#"+str_ulId);
			//根据array_customFun增加新的按钮
			if(array_customFun && typeof(array_customFun) !=  "undefined" && array_customFun.length > 0 ){
		    	console.log(array_customFun);
		    	$.each(array_customFun, function() {
		    		var self=this;
		    		var index=1;
		    		var str_customLi=[ "<li style=\"margin-bottom:20px,margin-left: 0px;\">",
										"<input type=\"button\" id=\""+str_idPrefix+"-ldrdSelect-btn"+index+"\" value=\""+self.label+"\" style=\"width: 55px;height: 25px;\" /></li>",
										"<li>"].join("");
					var jq_customLi=$(str_customLi);
					self.func();
					console.log(self);
					jq_ul.append(jq_customLi);
					$("#"+str_idPrefix+"-ldrdSelect-btn"+1).on("click",function(){
						self.func();
					});
		    	});
			} 	
		}